package com.seckill.seckilldemo.vo;

import com.seckill.seckilldemo.utils.ValidatorUnit;
import com.seckill.seckilldemo.validator.IsMobile;
import org.thymeleaf.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class isMobileValidator implements ConstraintValidator<IsMobile,String> {

    private boolean required = false;
    @Override
    //初始化
    public void initialize(IsMobile constraintAnnotation) {
        //获取required的值
        required = constraintAnnotation.required();
        System.out.println("required"+required);
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if(required){
            return ValidatorUnit.isMobile(value);
        }else{ //不是必填的情况，为空也直接返回true
            if(StringUtils.isEmpty(value)){
                return true;
            }else{ //不为空再判断手机号
                return ValidatorUnit.isMobile(value);
            }
        }
    }
}
